import { ipcMain } from "electron";
import fs from "node:fs/promises";
import fss from "node:fs";
import path from "node:path";

// 读取文件,返回Buffer
ipcMain.handle("file:read", (_, ...args: Parameters<typeof fs.readFile>) => {
  if (!fss.existsSync(args[0] as string)) return Buffer.alloc(0);
  return fs.readFile(...args);
});

// 读取文件,返回文本
ipcMain.handle("file:read-text", async (_, ...args: Parameters<typeof fs.readFile>) => {
  if (!fss.existsSync(args[0] as string)) return "";
  return await fs.readFile(...args).then(data => data.toString());
});

// 写入文件
ipcMain.handle("file:write", async (_, ...args: Parameters<typeof fs.writeFile>) => {
  const file = args[0];
  if (typeof file === "string") {
    const dir = path.dirname(file);
    await fs.mkdir(dir, { recursive: true });
  }
  return await fs.writeFile(...args);
});

ipcMain.handle("file:copy-file", async (_, ...args: Parameters<typeof fs.copyFile>) => {
  if (!fss.existsSync(args[0])) return;
  const dest = args[1]!.toString();
  await fs.mkdir(path.dirname(dest), { recursive: true });
  await fs.copyFile(...args);
});

ipcMain.handle("file:exists", async (_, file: string) => fss.existsSync(file));
ipcMain.handle("file:delete", async (_, ...args: Parameters<typeof fss.rmSync>) => {
  try {
    fss.rmSync(...args);
    return true;
  } catch (e: any) {
    console.error(e);
    return false;
  }
});

ipcMain.handle("file:rename", async (_, ...args: Parameters<typeof fss.renameSync>) => {
  try {
    fss.renameSync(...args);
    return true;
  } catch (e: any) {
    console.error(e);
    return false;
  }
});

// symlink
ipcMain.handle("file:symlink", async (_, ...args: Parameters<typeof fss.symlinkSync>) => {
  try {
    const targetParentDir = path.dirname(args[1] as string);
    if (!fss.existsSync(targetParentDir)) {
      await fs.mkdir(targetParentDir, { recursive: true });
    }
    fss.symlinkSync(...args);
    return true;
  } catch (e: any) {
    console.error(e);
  }
});

ipcMain.handle("file:link", async (_, ...args: Parameters<typeof fss.linkSync>) => {
  try {
    const targetParentDir = path.dirname(args[1] as string);
    if (!fss.existsSync(targetParentDir)) {
      await fs.mkdir(targetParentDir, { recursive: true });
    }
    fss.linkSync(...args);
    return true;
  } catch (e: any) {
    console.error(e);
    return false;
  }
});

ipcMain.handle("file:unlink", async (_, ...args: Parameters<typeof fss.unlinkSync>) => {
  try {
    fss.unlinkSync(...args);
    return true;
  } catch (e: any) {
    console.error(e);
    return false;
  }
});

ipcMain.handle("file:readdir", async (_, ...args: Parameters<typeof fss.readdirSync>) => {
  if (!fss.existsSync(args[0])) return [];
  return fss.readdirSync(...args);
});
